package com.yujistu.fragment;

import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.yujistu.App;
import com.yujistu.R;
import com.yujistu.adapter.BaseListAdapter;
import com.yujistu.framework.helper.BaseHelper;
import com.yujistu.model.BaseModel;
import com.yujistu.utils.IListUI;
import com.yujistu.utils.TLog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.InjectView;
import cz.msebera.android.httpclient.Header;


/**
 * Created by Win on 2015/11/5.
 */
public abstract class BaseFragment<T extends BaseModel> extends BaseItemFragment implements
        SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener,IListUI {

    @InjectView(R.id.swipe_container)
    public SwipeRefreshLayout swipe_container;
    @InjectView(R.id.list_view)
    public ListView mListView;
    @InjectView(R.id.top_layoutRL)
    protected RelativeLayout mTopLayoutView;

    public final int LIMIT = 10;

    private int mPage = 1;
    protected BaseListAdapter mAdapter;
    private LinearLayout mFooter;
    private TextView mListViewFooter;
    private int mVisibleLastIndex = 0; // 最后的可视项索引
    private int mPageCurrent = mPage;    //当前已经加载的页面数量
    protected boolean isLoading = false;
    protected boolean isLoadingOver = false;
    private boolean isFirstIn = true;

    protected String getURL() {
        return "";
    }

    private AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onStart() {
            TLog.log("新闻页Api：" + getRequestURI());
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String jsonStr = new String(responseBody);
            try {
                JSONObject objectBody = new JSONObject(jsonStr);
                if (objectBody.getString("success") != null){
                    JSONObject object = objectBody.getJSONObject("data");
                    String resStr = object.getString(getJsonArrayName());
                    ArrayList<T> list = getArrayList(resStr);
                    if (mPage == 1 && list.size() == 0) {
                        setNoneViewVisible();
                    } else {
                        setNoneViewGone();
                    }
                    if (mPage == 1) {
                        mAdapter.setData(list);
                    } else {
                        mAdapter.addData(list);
                    }
                    if (list.size() < getLimit()) {
                        isLoadingOver = true;
                    }
                    TLog.log("mPage：" + mPage);
                    mPage++;
                    mPageCurrent = mPage;
                    swipe_container.setVisibility(View.VISIBLE);
                }else {
                    doFail();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            doFail();
        }

        @Override
        public void onFinish() {
            super.onFinish();
            isLoading = false;
            swipe_container.setRefreshing(false);
        }
    };

    private void doFail() {
        if (mAdapter.getCount() > 0) {
            if (mPage == 1) {
                Toast.makeText(getApplication(), "刷新失败，请重试", Toast.LENGTH_SHORT).show();
            } else {
                mListViewFooter.setText(IListUI.LOADING_FAILURE);
                mFooter.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mListViewFooter.setText(IListUI.TEXT_LOADING);
                        mPage = mPageCurrent;
                        loadData(false);
                    }
                });
            }
        } else {
//                mLoadErrorView.setVisibility(View.VISIBLE);
            mTopLayoutView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                        mLoadErrorView.setVisibility(View.GONE);
                    loadData(true);
                }
            });
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_base_list;
    }

    @Override
    public void initView(View view) {
      //  swipe_container = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
        swipe_container.setOnRefreshListener(this);
        if (mAdapter != null) {
            mListView.setAdapter(mAdapter);
        } else {
            mAdapter = getListAdapter();
            mListView.setAdapter(mAdapter);
        }
        if (needDivider()) {
            mListView.setDividerHeight(1);
        } else {
            mListView.setDividerHeight(0);
        }
     //   mListView.setDivider(App.getInstance().getResources().getDrawable(R.drawable.selector_gradient_down));
        mFooter = (LinearLayout) LayoutInflater.from(getActivity())
                .inflate(R.layout.view_base_list_view_footer, null);
        mListViewFooter = (TextView) mFooter.findViewById(R.id.tv_footer);
        if (needMorePages()) { //需要分页的
            mListView.addFooterView(mFooter, null, false);
            mListView.setFooterDividersEnabled(false);
            mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem,
                                     int visibleItemCount, int totalItemCount) {
                    mVisibleLastIndex = firstVisibleItem + visibleItemCount - 1;
                    scrollFunction(firstVisibleItem);
                }

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    int itemsLastIndex = mAdapter.getCount() - 1; // 数据集最后一项的索引
                    int lastIndex = itemsLastIndex
                            + mListView.getHeaderViewsCount() + mListView.getFooterViewsCount() -1;
                    if (isLoadingOver) {
                        mListViewFooter.setText(IListUI.TEXT_LOAD_ALL_DATA);
                        return;
                    }
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                            && mVisibleLastIndex == lastIndex) {
                        mListViewFooter.setText(IListUI.TEXT_LOADING);
                        // 自动加载,放置异步加载数据的代码
                        mPage = mPageCurrent;
                        loadData(false);
                    } else {
                        if (isLoading) {
                            return;
                        }
                        mListViewFooter.setText(IListUI.TEXT_LOADING_UP);
                    }
                }
            });
        }
        mListView.setOnItemClickListener(this);
    }

    /**
     * listView滚动事件拓展 *
     */
    private void scrollFunction(int firstVisibleItem) {

    }

    public abstract BaseListAdapter<T> getListAdapter();

    /**
     * 获取gson解析后的数据
     *
     * @param jsonStr
     * @return
     */
    public ArrayList<T> getArrayList(String jsonStr) {
        return new ArrayList<T>();
    }

    //是否需要分页
    protected boolean needMorePages() {
        return true;
    }

    //每页数据条数
    protected int getLimit() {
        return LIMIT;
    }

    //是否需要分割线
    protected boolean needDivider() {
        return true;
    }

    @Override
    public void setNoneViewVisible() {

    }

    @Override
    public void setNoneViewGone() {

    }

    protected String getJsonArrayName(){
        return "";
    }
    @Override
    public void getJsonObject(JSONObject jsonObject) {

    }

    public void loadData(boolean isShowProgressBar) {

        if (isLoading) {
            return;
        }

        isLoading = true;

        if (isShowProgressBar) {

        }

        if (mAdapter.getCount() == 0) {
            swipe_container.setVisibility(View.GONE);
        }
        askApi();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
       /* if(isFirstOne())
            isFirstIn = false;
        if(getView() != null){
            if(isVisibleToUser && isFirstIn){
                loadData(true);
                isFirstIn=false;
            }
        }*/
    }

    private boolean isFirstOne() {
        return false;
    }

    public void askApi() {
        BaseHelper.getList(getURL(), mPage, getLimit(), mHandler);
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }

    @Override
    public void onRefresh() {
         loadData(false);
    }
}
